package no.ntnu.fp.server;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

import no.ntnu.fp.model.AbstractModel;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.SuperPackage;
import no.ntnu.fp.net.co.Connection;
import nu.xom.Document;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class Server {
	
	private TCPListener tcpListener;
	private ModelHandler modelHandler;
	private List<ConnectionHandler> clients;
	
	public Server() {
		
		modelHandler = new ModelHandler();
		clients = new LinkedList<ConnectionHandler>();
		tcpListener = new TCPListener(this);
		startListener();
	}
	
	public synchronized void addClient(Socket socket) {
		System.out.println("New client added");
		ConnectionHandler c = new ConnectionHandler(socket, this);
		clients.add(c);
		modelHandler.transferModelsToClient(c);
	}
	
	public synchronized void dataFromClient(String s, ConnectionHandler sourceClient) {
		System.err.println("SERVER:" + s);
		modelHandler.updateModel(s);
		//notifyModelChanged(s, sourceClient);
		
	}
	
	private void notifyModelChanged(String s, ConnectionHandler sourceClient) {
		
		for (ConnectionHandler client : clients) {
			
			if (client != sourceClient) {
				client.send(s);
			}
		}
	}
	
	private void startListener() {
		
		new Thread(tcpListener).start();
	}
	
	public static void main(String[] args) {
		new Server();
	}
}
